import React from 'react';
import {
  Alert, Card, Col, Input, InputNumber,
  Modal, Radio, Row, Spin, Tag,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { IconButton, PageHeaderLayout } from '../../components';
import { modalWidth } from '../../../config';
import tools from '../../utils';
import Authorized from '../../utils/Authorized';
import styles from './dormitory.css';

const basicName = '宿舍';
const reqApi = 'dormitory';
const formItemLayout2 = {
  labelCol: { md: 6, xs: 8 },
  wrapperCol: { md: 18, xs: 16 },
};

class page extends React.Component {
  state = {
    loading: false,
    visible: false,
    dialogLoading: false,
    dialogTitle: "",
    dialogAction: "",
    editId: 0,
    beforeName: '', // 编辑时记录初始值
  };

  componentDidMount() {
    this.funcGetListData();
  }

  // 获取列表数据
  funcGetListData = () => {
    this.setState({ loading: true });

    const { props } = this;

    props.dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: 1,
        pageSize: 1000,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const act = record ? "edit" : "create";
    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle(basicName, act),
      dialogAction: act,
    }, () => {
      const { props } = this;
      if (act === "edit") {
        const { name, remark, type, size } = record;
        props.form.setFieldsValue({
          name,
          remark,
          type,
          size,
        });
        this.setState({ beforeName: name });
      } else {
        const type = props.form.getFieldValue('type');
        props.form.resetFields();
        props.form.setFieldsValue({ type }); // "宿舍类型"仍沿用上次的值, 方便批量新增
      }
    });
  };

  // 删除
  funcDelete = (e, id, name) => {
    e.preventDefault();

    Modal.confirm({
      title: '删除？',
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{name}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + "/dele",
          payload: { ids: id },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
        });
      },
    });
  };

  // 保存
  funcSave = () => {
    const { state } = this;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const model = { ...values };
      const action = state.dialogAction;
      if (action === "edit") {
        model.id = state.editId;
      }

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/' + action,
        payload: { action, model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 自定义的小标签
  myTag = (item) => {
    const { props } = this;
    const { id, name, type } = item;
    return (
      <Tag
        key={id}
        closable={tools.funcCheckValid(props, 'delete')}
        onClose={(e) => this.funcDelete(e, id, name)}
        onClick={tools.funcCheckValid(props, 'edit') ? () => {
          this.setState({ editId: id });
          this.funcOpenForm(item);
        } : null}
        style={{ marginBottom: 8 }}
        color={type === '1' ? '#1890ff' : '#f5222d'}
      >
        {name}
      </Tag>
    );
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;
    const { data, total } = props[reqApi];
    const data0 = [], data1 = [];

    data.map((item) => {
      if (item.type === '1') data1.push(item);
      else data0.push(item);
    });

    return (
      <PageHeaderLayout title={props.route.name}>
        <Card bordered={false}>
          <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
            <IconButton
              text={'新增' + basicName}
              onClick={() => this.funcOpenForm()}
              style={{ marginBottom: 16, marginRight: 16 }}
            />
          </Authorized>
          <span>
            {total ? '共 ' + total + ' 间' + basicName : '暂无' + basicName + ', 请新增'}
          </span>
          <Spin spinning={state.loading}>
            <Row gutter={24}>
              <Col md={12} sm={24}>
                <Alert
                  type='info'
                  message={(
                    <div className={styles.bg}>
                      <div className={styles.title}>
                        {'男生宿舍' + (data1.length ? ' ' + data1.length + '间' : '')}
                      </div>
                      {data1.map((item) => this.myTag(item))}
                    </div>
                  )}
                />
              </Col>

              <Col md={12} sm={24}>
                <Alert
                  type='error'
                  message={(
                    <div className={styles.bg}>
                      <div className={styles.title}>
                        {'女生宿舍' + (data0.length ? ' ' + data0.length + '间' : '')}
                      </div>
                      {data0.map((item) => this.myTag(item))}
                    </div>
                  )}
                />
              </Col>
            </Row>
          </Spin>
        </Card>

        <Modal
          width={modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoading}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label='宿舍房间号' {...formItemLayout2}>
                  {getFieldDecorator("name", {
                    rules: [{ required: true, message: '请输入宿舍房间号' }],
                  })(<Input maxLength={10} autoFocus />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="宿舍楼" {...formItemLayout2}>
                  {getFieldDecorator("type", { initialValue: '1' })(
                    <Radio.Group buttonStyle="solid">
                      <Radio.Button value='1'>
                        <Icon type="man" />
                        <span> 男生</span>
                      </Radio.Button>
                      <Radio.Button value='0'>
                        <Icon type="woman" />
                        <span> 女生</span>
                      </Radio.Button>
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="容纳人数" {...formItemLayout2}>
                  {getFieldDecorator("size", { initialValue: 8 })(
                    <InputNumber min={0} max={8} step={2} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="备注" {...formItemLayout2}>
                  {getFieldDecorator("remark")(
                    <Input.TextArea maxLength={255} rows={1} />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ dormitory, menu }) => ({ dormitory, menu }))(page2);
